﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Irvin_Engine.State
{
    public class StateManager
    {
        private List<GameState> gameStates = new List<GameState>();
        private List<GameState> popupStates = new List<GameState>();
        private List<GameState> screensActives = new List<GameState>();
        private List<GameState> popupActives = new List<GameState>();
        private GameState currentState = null;

        static private StateManager m_oSingleton = null;

        public GameState CurrentState
        {
            get { return currentState; }
            set { currentState = value; }
        }

        private StateManager()
        {
        }

        static public StateManager GetSingleton()
        {
            if (m_oSingleton == null)
                m_oSingleton = new StateManager();
            return m_oSingleton;
        }

        public void InitializeState(GameState gameState, TypeState typeState)
        {
            if (typeState == TypeState.GAMESTATE)
            {
                gameStates.Add(gameState);
            }
            else if (typeState == TypeState.POPUP)
            {
                popupStates.Add(gameState);
            }
        }

        public void Update(GameTime _gameTime)
        {
            screensActives.Clear();
            popupActives.Clear();
            // Remplir tous les GameState actifs dans les screensActives
            for(int i = 0; i < gameStates.Count; i++)
            {
                if (gameStates[i].IsActive && gameStates[i].TypeState == TypeState.GAMESTATE)
                    screensActives.Add(gameStates[i]);

                else if (gameStates[i].IsActive && gameStates[i].TypeState == TypeState.POPUP)
                    popupActives.Add(gameStates[i]);
            }


            for (int i = 0; i < popupActives.Count; i++)
                popupActives[i].Update(_gameTime);

                // Update l'ecran actuel
                currentState.Update(_gameTime);
        }

        public void SwitchTo(string _previousState, string _futurState)
        {
            for (int i = 0; i < gameStates.Count; i++)
            {
                if (_previousState == gameStates[i].GetID())
                {
                    gameStates[i].IsActive = false;
                }
                else if (_futurState == gameStates[i].GetID())
                {
                    gameStates[i].IsActive = true;
                }
            }
        }

        public void Draw(GameTime _gameTime)
        {
            for(int i = 0; i< screensActives.Count; i++)
            {
                screensActives[i].Draw(_gameTime);
            }
        }
    }
}
